package com.chinamobile.ln.ictenterprises.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.annotation.SuppressLint;
import android.text.Html;
import android.text.Spanned;

/**
 * String帮助类
 * @author FuLei
 * 
 */
@SuppressLint("SimpleDateFormat")
@SuppressWarnings("unused")
public class StringUtil {

    private static final boolean FLAG_FALSE = false;

    private static final boolean FLAG_TRUE = true;

    static final String array[] = new String[] { "ABCabc2", "DEFdef3", "GHIghi4", "JKLjkl5", "MNOmno6", "PQRSpqrs7", "TUVtuv8", "WXYZwxyz9" };

    /**
     * 判断传入的字符串是否为空，其中，str="null"与str="NULL"均视为空值
     * @param str
     * @return 传入的字符串为空返回true，反之返回flase
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str)) {
            return FLAG_TRUE;
        }
        else {
            return FLAG_FALSE;
        }
    }

    /**
     * 判断传入的字符串是否不为空
     * @param str
     * @return 传入的字符串不为空返回true，反之返回false
     */
    public static boolean isNotEmpty(String str) {
        if (str != null && !"".equalsIgnoreCase(str)) {
            return FLAG_TRUE;
        }
        else {
            return FLAG_FALSE;
        }

    }

    /**
     * 获取元素在数组的下标
     * @param arr String数据
     * @param item 元素名
     * @return 数组下标，如果数组中找不到则返回-1
     */
    public static int getIndex(String[] arr, String item) {
        int index = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equalsIgnoreCase(item)) {
                index = i;
                break;
            }
        }
        return index;
    }

    /**
     * 验证传入的11位手机号是否正确
     * @param mobiles
     * @return
     */
    public static boolean isMobileNum11(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[^4,\\D])|(147))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    
    /**
     * 验证字符串是否由字母+数字组成，强验证
     * @param pwd
     * @return
     */
    public static boolean isValidPwd(String str){
        Pattern p = Pattern.compile("((^[0-9]+[a-zA-z]+([0-9a-zA-Z])*$)|(^[a-zA-z]+[0-9]+([0-9a-zA-Z])*$))");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * MD5加密，32位
     * @param str
     * @return
     */
    public static String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static boolean numberMatch(String string, String s) {
        if (null == string)
            return false;
        String dealStr = string.replace("-", "");
        dealStr = dealStr.replace(" ", "");
        if (dealStr.contains(s))
            return true;
        return false;
    }

    /**
     * 小写字符转换为大写字符
     * @param c
     * @return
     */
    public static char conversionHeadUppercase(char c) {
        switch (c) {
        case 'a':
            return 'A';
        case 'b':
            return 'B';
        case 'c':
            return 'C';
        case 'd':
            return 'D';
        case 'e':
            return 'E';
        case 'f':
            return 'F';
        case 'g':
            return 'G';
        case 'h':
            return 'H';
        case 'i':
            return 'I';
        case 'j':
            return 'J';
        case 'k':
            return 'K';
        case 'l':
            return 'L';
        case 'm':
            return 'M';
        case 'n':
            return 'N';
        case 'o':
            return 'O';
        case 'p':
            return 'P';
        case 'q':
            return 'Q';
        case 'r':
            return 'R';
        case 's':
            return 'S';
        case 't':
            return 'T';
        case 'u':
            return 'U';
        case 'v':
            return 'V';
        case 'w':
            return 'W';
        case 'x':
            return 'X';
        case 'y':
            return 'Y';
        case 'z':
            return 'Z';
        default:
            return c;
        }
    }
    
    public static char letterToNumber(char ch){
        switch (ch) {
        case 'a':
            return '2';
        case 'b':
            return '2';
        case 'c':
            return '2';
        case 'd':
            return '3';
        case 'e':
            return '3';
        case 'f':
            return '3';
        case 'g':
            return '4';
        case 'h':
            return '4';
        case 'i':
            return '4';
        case 'j':
            return '5';
        case 'k':
            return '5';
        case 'l':
            return '5';
        case 'm':
            return '6';
        case 'n':
            return '6';
        case 'o':
            return '6';
        case 'p':
            return '7';
        case 'q':
            return '7';
        case 'r':
            return '7';
        case 's':
            return '7';
        case 't':
            return '8';
        case 'u':
            return '8';
        case 'v':
            return '8';
        case 'w':
            return '9';
        case 'x':
            return '9';
        case 'y':
            return '9';
        case 'z':
            return '9';
        default:
            return ch;
        }
    }

    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 替换掉中文字符
     * @param chines
     * @return
     */
    public static String replaceString(String chines) {
        return chines.replace("《", "").replace("》", "").replace("！", "").replace("￥", "").replace("【", "").replace("】", "").replace("（", "").replace("）", "").replace("－", "").replace("；", "")
            .replace("：", "").replace("”", "").replace("“", "").replace("。", "").replace("，", "").replace("、", "").replace("？", "").replace(" ", "").replace("-", "");
    }

   

  
  

   

  
  
    /**
     * 首字母是否有英文
     * 
     * @param str
     * @return
     */
    public static boolean isEng(String str) {
        if (str != null && str.length() > 0) {
            return str.charAt(0) >= 0x0000 && str.charAt(0) <= 0x00ff;
        }
        else {
            return false;
        }
    }

    /**
     * 将List&lt;String>转换为数组
     * @param list
     * @return
     */
    public static String[] list2Arr(List<String> list) {
        String[] arr = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    /**
     * 将日期Time转换为日期字符串
     * @param time
     * @param format 格式 MM月dd日 HH:mm
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatDate2String(long time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }

   

    /**
     * 获取当前日期的前几天或者后几天
     * @param interval 整数为后几天，负数为前几天
     * @return
     */
    public static String getFromNowDate(int interval) {
        Date date = new Date();// 取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, interval);// 把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); // 这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        return formatter.format(date);
    }

    /**
     * 获取当前时间
     * @param format 格式
     * @return
     */
    public static String getNowDate(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        sdf.format(new Date());
        return sdf.format(new Date());
    }

    /**
     * 
     * @param str
     * @return
     */
    public static String getDateStr(String str, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        String date = "";
        try {
            Date d = sdf.parse(str);
            date = formatDate2String(d.getTime(), format);
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将日期转换为time
     * @param date 格式：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static long date2time(String date) {
        long dtime = 0L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA);
        try {
            Date d = sdf.parse(date);
            dtime = d.getTime();
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return dtime;
    }

    public static String getFormatDate(String dateStr, String format) {
        String newDateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
        try {
            Date date = sdf.parse(dateStr);
            newDateStr = formatDate2String(date.getTime(), format);
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return newDateStr;
    }

    /**
     * 转换yyyyMMddHHmmss日期为指定分隔符的日期
     * @param dateStr
     * @param format
     * @return
     */
    public static String getFormatDateTime(String dateStr, String format) {
        String newDateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        try {
            Date date = sdf.parse(dateStr);
            newDateStr = formatDate2String(date.getTime(), format);
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return newDateStr;
    }

    /**
     * 将号码的无效部分过滤掉
     * @param number
     * @return
     */
    public static String filterNumber(String number) {
        if (isNotEmpty(number)) {
            if (number.startsWith("+86")) {
                number = number.substring(3).trim();
            }
            else if (number.startsWith("17951") || number.startsWith("17911") || number.startsWith("17909") || number.startsWith("11808")) {
                number = number.substring(5).trim();
            }
            if (number.startsWith("0")) {
                number = number.substring(1).trim();
            }
        }
        return number;
    }

    /**
     * 返回byte的数据大小对应的文本
     * 
     * @param size
     * @return
     */
    public static String getDataSize(long size) {
        if (size < 0) {
            size = 0;
        }
        DecimalFormat formater = new DecimalFormat("####.00");
        if (size < 1024) {
            return size + "B";
        }
        else if (size < 1024 * 1024) {
            float kbsize = size / 1024f;
            return formater.format(kbsize) + "KB";
        }
        else if (size < 1024 * 1024 * 1024) {
            float mbsize = size / 1024f / 1024f;
            return formater.format(mbsize) + "MB";
        }
        else if (size < 1024 * 1024 * 1024 * 1024) {
            float gbsize = size / 1024f / 1024f / 1024f;
            return formater.format(gbsize) + "GB";
        }
        else {
            return "size: error";
        }
    }

    /**
     * 截取固定长度的字符串
     * @param str 需要截取的字符串
     * @param len 截取长度
     * @return
     */
    public static String subStr(String str, int len) {
        if (isEmpty(str)) {
            return "";
        }
        int reInt = 0;
        String reStr = "";
        char[] tempChar = str.toCharArray();
        for (int kk = 0; (kk < tempChar.length && len > reInt); kk++) {
            String s1 = String.valueOf(tempChar[kk]);
            byte[] b = s1.getBytes();
            reInt += b.length;
            reStr += tempChar[kk];
        }
        if (len == reInt || (len == reInt - 1))
            reStr += "a";
        return reStr;
    }

    /**
     * 获取传入日期与当前日期相差的天数
     * @param date
     * @return
     */
    public static int getDays(String date) {
        int days = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d1 = sdf.parse(date);
            Date d2 = new Date();
            days = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 获取手机IP
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex) {
        }
        return null;
    }

    /**
     * 获取字符串的长度，一个全角字符（包括汉字）算两个长度
     * @param str
     * @return
     */
    public static int getStringLength(String str) {
        str = str.replaceAll("[^\\x00-\\xff]", "**");
        int length = str.length();
        return length;
    }

    /**
     * 判断字符是否是汉字
     * @param str 单个汉字
     * @return
     */
    public static boolean isChinese(String str) {
        Pattern p = Pattern.compile("[^\\x00-\\xff]");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 判断字符串是否有汉字
     * @param str
     * @return
     */
    public static boolean hasChinese(String str) {
        return str.length() == str.getBytes().length ? false : true;
    }

    public static String getDateTime(String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }
}
